const I18nService = require('../services/i18nService');
const { formatResponse } = require('../utils/transform');
const fs = require('fs');

class I18nController {
  constructor() {
    this.i18nService = new I18nService();
  }

  async getI18nList(ctx) {
    try {
      const query = ctx.query || ctx.request.query || {};
      const result = await this.i18nService.getI18nList(query);
      if (result.success) {
        ctx.body = formatResponse(200, '获取成功', result.data);
      } else {
        ctx.body = formatResponse(result.status || 500, result.message || '获取失败', result.error);
      }
    } catch (error) {
      console.error('获取国际化数据列表控制器错误:', error);
      ctx.body = formatResponse(500, '获取失败', error.message);
    }
  }

  async createI18nData(ctx) {
    try {
      const { code, remarks, languageTexts } = ctx.request.body;
      const result = await this.i18nService.createI18nData(code, remarks, languageTexts);
      if (result.success) {
        ctx.body = formatResponse(200, '创建成功', result.data);
      } else {
        ctx.body = formatResponse(result.status || 500, result.message || '创建失败', result.error);
      }
    } catch (error) {
      console.error('创建国际化数据控制器错误:', error);
      ctx.body = formatResponse(500, '创建失败', error.message);
    }
  }

  async updateI18nData(ctx) {
    try {
      const { code, remarks, languageTexts } = ctx.request.body;
      const result = await this.i18nService.updateI18nData(code, remarks, languageTexts);
      if (result.success) {
        ctx.body = formatResponse(200, '更新成功', result.data);
      } else {
        ctx.body = formatResponse(result.status || 500, result.message || '更新失败', result.error);
      }
    } catch (error) {
      console.error('更新国际化数据控制器错误:', error);
      ctx.body = formatResponse(500, '更新失败', error.message);
    }
  }

  async deleteI18nData(ctx) {
    try {
      const { code } = ctx.params;
      const result = await this.i18nService.deleteI18nData(code);
      if (result.success) {
        ctx.body = formatResponse(200, '删除成功', null);
      } else {
        ctx.body = formatResponse(result.status || 500, result.message || '删除失败', result.error);
      }
    } catch (error) {
      console.error('删除国际化数据控制器错误:', error);
      ctx.body = formatResponse(500, '删除失败', error.message);
    }
  }

  async getI18nDataByLanguageTag(ctx) {
    try {
      const { languageTag } = ctx.params;
      const result = await this.i18nService.getI18nDataByLanguageTag(languageTag);
      if (result.success) {
        ctx.body = formatResponse(200, '获取成功', result.data);
      } else {
        ctx.body = formatResponse(result.status || 500, result.message || '获取失败', result.error);
      }
    } catch (error) {
      console.error('获取指定语言国际化数据控制器错误:', error);
      ctx.body = formatResponse(500, '获取失败', error.message);
    }
  }

  // 导入国际化数据
  async importI18nData(ctx) {
    try {
      const { format } = ctx.request.body || {};
      const file = (ctx.req && ctx.req.file) || ctx.file;

      if (!file) {
        ctx.body = formatResponse(400, '请使用 multipart/form-data 上传 .json 或 .csv 文件', null);
        return;
      }

      const name = (file.originalname || '').toLowerCase();
      const mimetype = (file.mimetype || '').toLowerCase();
      const buf = file.buffer;
      let text = '';
      if (buf && Buffer.isBuffer(buf)) {
        text = buf.toString('utf-8');
      } else if (file.path) {
        try {
          text = fs.readFileSync(file.path, 'utf-8');
        } catch (e) {
          ctx.body = formatResponse(500, '读取上传文件失败', e.message);
          return;
        }
      }

      const fmtRaw = (ctx.request.body && ctx.request.body.format) || '';
      const fmt = String(fmtRaw).toLowerCase();
      const isJson = mimetype.includes('json') || name.endsWith('.json') || fmt === 'json';
      const isCsv = mimetype.includes('csv') || name.endsWith('.csv') || fmt === 'csv';

      let result;
      if (isJson) {
        let parsed;
        try {
          parsed = JSON.parse(text);
        } catch (e) {
          ctx.body = formatResponse(400, 'JSON文件解析失败', e.message);
          return;
        }
        let itemsPayload;
        if (Array.isArray(parsed)) {
          itemsPayload = parsed;
        } else if (Array.isArray(parsed.items)) {
          itemsPayload = parsed.items;
        } else if (parsed && parsed.code && parsed.languageTexts) {
          itemsPayload = [parsed];
        } else {
          ctx.body = formatResponse(400, 'JSON结构不合法，应为 items 数组或数组', null);
          return;
        }
        result = await this.i18nService.importI18nData({ format: 'json', items: itemsPayload });
      } else if (isCsv) {
        if (!text || typeof text !== 'string') {
          ctx.body = formatResponse(400, 'CSV文件内容为空', null);
          return;
        }
        result = await this.i18nService.importI18nData({ format: 'csv', content: text });
      } else {
        ctx.body = formatResponse(400, '不支持的文件类型，请上传 .json 或 .csv', { mimetype, name });
        return;
      }

      if (result.success) {
        ctx.body = formatResponse(200, '导入成功', result.data);
      } else {
        ctx.body = formatResponse(result.status || 500, result.message || '导入失败', result.error);
      }
    } catch (error) {
      console.error('导入国际化数据控制器错误:', error);
      ctx.body = formatResponse(500, '导入失败', error.message);
    }
  }

  // 导出国际化数据（支持 download=true 直接下载）
  async exportI18nData(ctx) {
    try {
      const { format = 'json', languageTags, download, filename } = ctx.request.query || {};
      const tags = typeof languageTags === 'string' ? languageTags.split(',').map(s => s.trim()).filter(Boolean) : languageTags;
      const result = await this.i18nService.exportI18nData({ format, languageTags: tags });

      if (!result.success) {
        ctx.body = formatResponse(result.status || 500, result.message || '导出失败', result.error);
        return;
      }

      const shouldDownload = String(download).toLowerCase() === 'true';
      const baseName = filename && String(filename).trim() ? String(filename).trim() : 'i18n_export';

      if (shouldDownload) {
        if (format === 'csv') {
          const content = result.data?.content || '';
          ctx.set('Content-Type', 'text/csv; charset=utf-8');
          ctx.set('Content-Disposition', `attachment; filename="${baseName}.csv"`);
          ctx.body = content;
          return;
        } else {
          // 默认 JSON
          const items = result.data?.items || [];
          const jsonStr = JSON.stringify(items, null, 2);
          ctx.set('Content-Type', 'application/json; charset=utf-8');
          ctx.set('Content-Disposition', `attachment; filename="${baseName}.json"`);
          ctx.body = jsonStr;
          return;
        }
      }

      // 常规JSON响应
      ctx.body = formatResponse(200, '导出成功', result.data);
    } catch (error) {
      console.error('导出国际化数据控制器错误:', error);
      ctx.body = formatResponse(500, '导出失败', error.message);
    }
  }
}

module.exports = I18nController;